'use strict';

const Service = require('egg').Service;

class UserRoleService extends Service {


  // 获取列表
  async findAll(pageNum, pageSize) {
    const { app } = this;
    try {
      const offset = (pageNum - 1) * pageSize;
      const { count, rows } = await app.model.RolePermission.findAndCountAll({
        offset,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 获取某个 资源
  async findOne(id) {
    return await this.app.model.RolePermission.findOne({ where: { id } });
  }

  // 新增
  async create(payload) {
    const { app } = this;
    return await app.model.RolePermission.create(payload);
  }
  // 修改
  async updated(id, payload) {
    const { app } = this;
    return await app.model.RolePermission.update(payload, { where: { id } });
  }


  // 删除
  async del(payload) {
    const { app } = this;
    const delData = await app.model.RolePermission.findAll({
      where: { id: payload.ids },
    });
    return await app.model.RolePermission.destroy({ where: { id: payload.ids }, delData, force: true });
  }

  /**
   *  单角色批量添加多菜单
   * @param payload
   * @return {Promise<void>}
   */
  async bulkCreatePremission(payload) {
    const { app } = this;
    payload = payload.permission_ids.map(e => {
      return { role_id: payload.role_id, permission_id: e };
    });
    return await app.model.RolePermission.bulkCreate(payload);
  }


}

module.exports = UserRoleService;
